import { Res, WebSocketClass } from '@/utils/socket';
import { SoundOutlined } from '@ant-design/icons';
import { history, useModel } from '@umijs/max';
import { Empty, notification, Popover } from 'antd';
import { useEffect, useState } from 'react';
export default () => {
  const [api, contextHolder] = notification.useNotification();
  const { initialState }: any = useModel('@@initialState');
  let userid = initialState?.currentUser?.userid || '';
  let role = initialState?.currentUser?.roleId || [];
  const [infoList, setinfoList]: any = useState(
    JSON.parse(localStorage.getItem('infoList' + userid) || '[]'),
  );
  function Notif(val: any) {
    let info = JSON.parse(val);
    api.info({
      message: `消息提醒`,
      description: (
        <div
        // onClick={() => {
        //   handleItemClick(val);
        // }}
        >
          {info.content}
        </div>
      ),
    });
  }
  function handleOldInfo(oldInfo: any, val: Res) {
    if (oldInfo) {
      localStorage.setItem('infoList' + userid, JSON.stringify([...oldInfo, val]));
    } else {
      localStorage.setItem('infoList' + userid, JSON.stringify([val]));
    }
    setinfoList(JSON.parse(localStorage.getItem('infoList' + userid) || '[]'));
  }
  function initSocket() {
    try {
      const ws = new WebSocketClass(
        process.env.REACT_SOCKET_URL + `/api/websocket/${userid}`,
        async (val) => {
          let oldInfo = JSON.parse(localStorage.getItem('infoList' + userid));
          handleOldInfo(oldInfo, val);
          Notif(val);
        },
        '理赔消息',
      );
      try {
        // 建立连接
        ws.connect('ping');
      } catch (error) {}
    } catch (error) {}
  }
  useEffect(() => {
    initSocket();
  }, []);
  function handleItemClick(item: any) {
    try {
      let oldInfo = JSON.parse(localStorage.getItem('infoList' + userid));
      oldInfo.map((e: any, i: number) => {
        if (JSON.parse(e).content === JSON.parse(item).content) {
          oldInfo.splice(i, 1);
          localStorage.setItem('infoList' + userid, JSON.stringify([...oldInfo]));
          setinfoList(oldInfo);
          let info = JSON.parse(item);
          let caseNo = info.content.split('案件号：【')[1].split('】，请及时处理！')[0];
          console.log(caseNo);
          history.push(
            {
              pathname: '/case/caseDetail',
            },
            {
              caseNo: caseNo,
              queryType: '2',
            },
          );
        }
      });
    } catch (error) {}
  }
  return (
    <div className="WebsocketBox">
      <Popover
        content={
          <div className="WebsocketBox_InfoList">
            {infoList.length === 0 ? (
              <Empty />
            ) : (
              <div>
                {infoList.map((item: any, index: number) => {
                  return (
                    <div
                      onClick={() => {
                        handleItemClick(item);
                      }}
                      key={index}
                      className="WebsocketBox_InfoList_Item"
                    >
                      {JSON.parse(item).content}
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        }
        title={''}
        trigger="click"
      >
        {contextHolder}
        {infoList.length > 0 ? <span className="number">{infoList.length}</span> : null}
        <SoundOutlined />
      </Popover>
    </div>
  );
};
